# coding=utf-8
from functools import wraps
import hashlib
from uuid import uuid4
from itsdangerous import URLSafeSerializer
from flask import current_app as app, g, redirect, abort

def uuid():
    '''
    获取uuid，返回字符串去除了“-”连接符
    '''
    return str(uuid4()).replace('-', '')

def md5(raw):
    '''
    对字符串进行MD5加密
    '''
    m = hashlib.md5()
    m.update(raw)
    return m.hexdigest()

def set_cookie(resp, key, value, expires=None):
    '''
    设置加密cookie，会对cookie内容进行加密
    '''
    resp.set_cookie(key, get_signing_serializer().dumps(value), httponly=True, expires=expires)

def get_cookie(req, key):
    '''
    获取加密cookie
    '''
    content = req.cookies.get(key)
    if not content:
        return None
    return get_signing_serializer().loads(content)

def del_cookie(resp, key):
    '''
    删除临时cookie
    '''
    resp.set_cookie(key, expires=0)

_digest_method = hashlib.sha1
_key_derivation = 'hmac'
_salt = 'uzwan.cn'

def get_signing_serializer():
    '''
    加密序列化工具，借助于itsdangerous
    '''
    if not app.secret_key:
        return None
    signer_kwargs = dict(
        key_derivation=_key_derivation,
        digest_method=_digest_method
    )
    return URLSafeSerializer(app.secret_key, salt=_salt, signer_kwargs=signer_kwargs)


def account_allow(logined=None, guest=None, to=None):
    def _func_wrapper(func):
        @wraps(func)
        def _arg_wrapper(*args, **kwargs):
            user = g.user
            if (user.logined == logined or logined == None) and (user.guest == guest or guest == None):
                return func(*args, **kwargs)
            if to:
                return redirect(to)
            abort(403)

        return _arg_wrapper

    return _func_wrapper